package top.huhuiyu.spirngboot2.total.aop;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.huhuiyu.spirngboot2.total.anno.Limit;
import top.huhuiyu.spirngboot2.total.exception.AppException;
import top.huhuiyu.spirngboot2.total.service.LimitService;

@Aspect
@Component
@Slf4j
@Order(11)
@RequiredArgsConstructor
public class LimitAop implements BaseControllerAop {
    private final LimitService limitService;

    @Before("controller()")
    public void before(JoinPoint jp) {
        // 获取被切面的方法信息
        MethodSignature ms = (MethodSignature) jp.getSignature();
        Limit limit = ms.getMethod().getAnnotation(Limit.class);
        if (limit == null) {
            log.debug("无需限流处理");
            return;
        }
        log.debug("limit的信息：{}", limit);
        boolean result = false;
        switch (limit.mode()) {
            case IP_BUCKET_LIMIT:
            case BUCKET_LIMIT:
                result = limitService.checkBucketLimit(limit);
                break;
            default:
                result = limitService.checkLimit(limit);
                break;
        }
        if (!result) {
            throw AppException.getInstance(limit.message());
        }
    }

}
